<?php
/**
 * 数据库管理
 *
 */
class Model_Databases {
	
	function __construct() {
	
	}
	
	/**
	 * 取得库中所有表数据
	 */
	public function listTables() {
		$config = Zend_Registry::get ( 'config' );
		$sql = "SHOW TABLE STATUS FROM `{$config->databases->app->config->dbname}` ";
		
		$DB_Table = new Cms_DbTable ();
		$tables = $DB_Table->getAdapter ()->query ( $sql )->fetchAll ( Zend_Db::FETCH_ASSOC );
		
		if (is_array ( $tables )) {
			foreach ( $tables as &$val ) {
				$val ['Size'] = sizecount ( $val ['Data_length'] + $val ['Index_length'] );
			}
		}
		return $tables;
	}
	
	/**
	 * 优化数据表
	 *
	 * @param $table_name string       	
	 */
	public function Operation($table_name) {
		$config = Zend_Registry::get ( 'config' );
		
		if (empty ( $table_name )) {
			$sql = "SHOW TABLE STATUS FROM `{$config->databases->app->config->dbname}` ";
			$DB_Table = new Cms_DbTable ();
			$tables = $DB_Table->getAdapter ()->query ( $sql )->fetchAll ( Zend_Db::FETCH_ASSOC );
			if (is_array ( $tables )) {
				foreach ( $tables as $val ) {
					$sql = "OPTIMIZE TABLE `{$val['Name']}`";
					$DB_Table->getAdapter ()->query ( $sql );
				}
			}
		} else {
			$sql = "OPTIMIZE TABLE `{$table_name}`";
			$DB_Table = new Cms_DbTable ();
			$DB_Table->getAdapter ()->query ( $sql );
		}
		return true;
	}
	
	/**
	 * 修复数据表
	 *
	 * @param $table_name string       	
	 */
	public function Repair($table_name) {
		$config = Zend_Registry::get ( 'config' );
		
		if (empty ( $table_name )) {
			$sql = "SHOW TABLE STATUS FROM `{$config->databases->app->config->dbname}` ";
			$DB_Table = new Cms_DbTable ();
			$tables = $DB_Table->getAdapter ()->query ( $sql )->fetchAll ( Zend_Db::FETCH_ASSOC );
			if (is_array ( $tables )) {
				foreach ( $tables as $val ) {
					$sql = "REPAIR TABLE `{$val['Name']}`";
					$DB_Table->getAdapter ()->query ( $sql );
				}
			}
		} else {
			$sql = "REPAIR TABLE `{$table_name}`";
			$DB_Table = new Cms_DbTable ();
			$DB_Table->getAdapter ()->query ( $sql );
		}
		return true;
	}
	
	/**
	 * 显示表结构
	 *
	 * @param $table_name string       	
	 */
	public function showTable($table_name) {
		if (empty ( $table_name )) {
			return false;
		}
		$sql = "SHOW CREATE TABLE `{$table_name}`";
		$DB_Table = new Cms_DbTable ();
		$data = $DB_Table->getAdapter ()->query ( $sql )->fetchAll ( Zend_Db::FETCH_ASSOC );
		return $data [0] ['Create Table'];
	}
	
	/**
	 * 备份数据库
	 */
	public function export() {
	
	}
}

?>